'use strict';
const base = require('../base/serviceBase');
const _ = require('lodash');
const {env} = require("echarts");
const moment = require("moment");
const {value} = require("lodash/seq");

module.exports = class extends base {
    /**
     * 室内温度评估
     * @returns {Promise<{status: string, result: *}>}
     * @param body
     */
    async inTempAssess(body) {
        const {ctx} = this;
        const {tenantCode} = body;
        const query = {$match: {status: 1, tenantCode, deviceType: "末端空调", "points.model": 0}};
        /**
         * 设定和环境温度平均值和最大值
         */
        const avg = await ctx.app.dbs.aggregate('IotDevice', [
            query,
            {
                $group: {
                    _id: null, // 分组键，这里使用null因为我们不需要按任何字段分组，只是求平均值
                    maxEnvTemp: {$max: "$points.envTemp"},
                    avgEnvTemp: {$avg: "$points.envTemp"}
                }
            }]);
        const avgEnvTemp = avg && avg.length > 0 && avg[0] ? avg[0].avgEnvTemp : 0;
        /**
         * 获取大于平均环境温度的数量
         */
        const totalRes = await ctx.app.dbs.aggregate('IotDevice', [
            query,
            {
                $match: {
                    "points.envTemp": {$gt: avgEnvTemp} // $gt 是大于的意思
                }
            },
            {
                $count: "gtAvg"
            }
        ]);


        const maxEnvTemp = avg && avg.length > 0 && avg[0] ? avg[0].maxEnvTemp : 0;
        const gtAvg = totalRes && totalRes.length > 0 && totalRes[0] ? totalRes[0].gtAvg : 0;

        const result = {
            avgEnvTemp,
            maxEnvTemp,
            gtAvg
        };

        return {
            status: 'ok',
            result
        };
    }

    async getSetTempAssess(body) {
        const {ctx} = this;
        const {tenantCode} = body;
        const query = {$match: {status: 1, tenantCode, deviceType: "末端空调", "points.model": 0}};

        /**
         * 获取设定值的平均值
         */
        const avgSet = await ctx.app.dbs.aggregate('IotDevice', [
            query,
            {
                $group: {
                    _id: null, // 分组键，这里使用null因为我们不需要按任何字段分组，只是求平均值
                    // minSetTemp: {min: "$points.setTemp"},
                    avgSetTemp: {$avg: "$points.setTemp"}
                }
            }]);

        /**
         * 获取设定值和环境值的平均差值和最大差值
         */
        const avgD = await ctx.app.dbs.aggregate('IotDevice', [
            query,
            {
                $project: {
                    difference: {$subtract: ["$points.envTemp", "$points.setTemp"]}
                }
            },
            {
                $group: {
                    _id: null, // 分组键，这里使用null因为我们不需要按任何字段分组，只是求平均值
                    maxDEnvTemp: {$max: "$difference"},
                    avgDEnvTemp: {$avg: "$difference"}
                }
            }
        ]);
        const avgDEnvTemp = avgD && avgD.length > 0 && avgD[0] ? avgD[0].avgDEnvTemp : 0;
        const maxDEnvTemp = avgD && avgD.length > 0 && avgD[0] ? avgD[0].maxDEnvTemp : 0;
        const avgSetTemp = avgSet && avgSet.length > 0 && avgSet[0] ? avgSet[0].avgSetTemp : 0;
        return {
            status: 'ok',
            result: {avgSetTemp, avgDEnvTemp, maxDEnvTemp}
        };
    }

    async getChillers(body) {
        const {ctx} = this;
        const {tenantCode} = body;
        const list = await ctx.app.dbs.find('IotDevice', {tenantCode, deviceType: {$regex: "制冷主机"}});
        const result = [];
        _.map(list, item => {
            const {deviceId} = item;
            if (!deviceId.includes("Meter")) {
                result.push(item);
            }
        });
        return {status: 'ok', result};
    }

    async getFreezingPumps(body) {
        const {ctx} = this;
        const {tenantCode} = body;
        const list = await ctx.app.dbs.find('IotDevice', {tenantCode, deviceType: {$regex: "冷冻水泵"}});
        const result = [];
        _.map(list, item => {
            const {deviceId} = item;
            if (!deviceId.includes("Meter")) {
                result.push(item);
            }
        });
        return {status: 'ok', result};
    }

    async getCoolingPumps(body) {
        const {ctx} = this;
        const {tenantCode} = body;
        const list = await ctx.app.dbs.find('IotDevice', {tenantCode, deviceType: {$regex: "冷却水泵"}});
        const result = [];
        _.map(list, item => {
            const {deviceId} = item;
            if (!deviceId.includes("Meter")) {
                result.push(item);
            }
        });
        return {status: 'ok', result};
    }

    async getAirZone(body) {
        const {ctx} = this;
        const {tenantCode} = body;
        const query = {status: 1, tenantCode, deviceType: "末端空调", "points.model": 0};
        const count = await ctx.app.dbs.count('IotDevice', {deviceType: "末端空调"});
        const runCount = await ctx.app.dbs.count('IotDevice', query);
        return {status: 'ok', result: {count, runCount}};
    }

    async getCross(body) {
        const {ctx} = this;
        const {tenantCode} = body;
        const query = {$match: {status: 1, tenantCode, deviceType: "末端空调", "points.model": 0}};
        /**
         * 获取大于25度的环境温度数量
         */
        const cross25Res = await ctx.app.dbs.aggregate('IotDevice', [
            query,
            {
                $match: {
                    "points.envTemp": {$gt: 25.5} // $gt 是大于的意思
                }
            },
            {
                $count: "cross25"
            }
        ]);

        /**
         * 获取环境温度大于设定温度的数量
         */
        const crossSetRes = await ctx.app.dbs.aggregate('IotDevice', [
            query,
            {
                $group: {
                    _id: null,  // 不对数据进行分组，直接计算整个集合的统计结果
                    crossSetCount: {$sum: {$cond: [{$gt: ["$points.envTemp", "$points.setTemp"]}, 1, 0]}}
                }
            }
        ]);

        let crossSet1Count = 0, crossSet2Count = 0;
        const res = await ctx.app.dbs.find("IotDevice", {status: 1, deviceType: "末端空调", "points.model": 0});
        _.map(res, value => {
            const {deviceId, points = {}} = value;
            const {setTemp, envTemp} = points;

            if (envTemp > setTemp + 1) {
                crossSet1Count++;
            }
            if (envTemp > setTemp + 2) {
                crossSet2Count++;
            }
        });
        const cross25 = cross25Res && cross25Res.length > 0 && cross25Res[0] ? cross25Res[0].cross25 : 0;
        const crossSetCount = crossSetRes && crossSetRes.length > 0 && crossSetRes[0] ? crossSetRes[0].crossSetCount : 0;
        return {status: 'ok', result: {cross25, crossSetCount, crossSet1Count, crossSet2Count}};
    }

    async getIceSys(body) {
        const {ctx} = this;
        const {tenantCode} = body;
        const list = await ctx.app.dbs.find('IotDevice', {tenantCode, deviceType: '制冷系统'});
        const result = {};
        _.map(list, item => {
            const {deviceId, status, statusPath, points} = item;
            if (status) result[deviceId + statusPath] = status;
            if (statusPath === 'accCoolingCapacity') {
                //   console.log('cooling capacity', points);
                _.map(points, (value, key) => {
                    result[deviceId + key] = value;
                });
            }
        });

        return {status: 'ok', result};
    }

    async getSysAssess(body) {
        const {ctx} = this;
        const {timeRange = [],timeSpace, tenantCode} = body;
        const start = moment(timeRange[0]).valueOf();
        const end = moment(timeRange[1]).valueOf();
        const query = {tenantCode, time: {$gt: start, $lt: end},timeSpace};
        console.log("get sys assess", query);
        const result = await ctx.app.dbs.find('Assess', query, {time: -1});

        return {status: 'ok', result};
    }

    async getPowerCockpit(body) {
        const {ctx} = this;
        const {timeRange = [], tenantCode} = body;
        const start = moment(timeRange[0]).valueOf();
        const end = moment(timeRange[1]).valueOf();
        const list = await ctx.app.dbs.find('Assess', {tenantCode, time: {$gt: start, $lt: end}});
        const result = [];

        _.map(list, item => {
            const {power, timeStr} = item;
            let _value = 0;
            const data = [];

            _.map(power, (it) => {
                const {deviceName} = it;
                const value = it.value ? parseFloat(it.value) : 0;
                _value += value;
                data.push({deviceName, value});
            });
            result.push({createdTime: timeStr, value: _value.toFixed(2), data});
        });
        return {status: 'ok', result};
    }

    async getCoolCockpit(body) {
        const {ctx} = this;

        const {timeRange = [], tenantCode} = body;
        const start = moment(timeRange[0]).valueOf();
        const end = moment(timeRange[1]).valueOf();
        const list = await ctx.app.dbs.find('Assess', {tenantCode, time: {$gt: start, $lt: end}});
        const result = [];

        _.map(list, item => {
            const {iceSys, timeStr} = item;
            const {FWSupplyTemptemp, FWBackTemptemp, coolingMeterinstantaneousTraffic} = iceSys;
            const value = coolingMeterinstantaneousTraffic * (FWSupplyTemptemp - FWBackTemptemp);
            result.push({createdTime: timeStr, value: value.toFixed(2)});
        });
        return {status: 'ok', result};
    }
};
